﻿using System;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace eDofE.Web.Helpers
{
    public class EnableJsonAttribute : ActionFilterAttribute
    {
        private readonly static string[] _jsonTypes = new string[] { "application/json", "text/json" };

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            try
            {
                if (typeof(RedirectToRouteResult).IsInstanceOfType(filterContext.Result))
                    return;

                //AcceptTypes -> this is the request header Accept : application/json

                var acceptTypes = filterContext.HttpContext.Request.AcceptTypes ?? new[] { "text/html" };
                var model = filterContext.Controller.ViewData.Model;
                if (filterContext.Exception != null)
                {
                    //if (filterContext.Exception.GetType().Name.Equals("BizException"))
                    //{
                    model = new
                    {
                        Success = false,
                        Message = filterContext.Exception.Message
                    };
                    //filterContext.Exception = null;
                    //filterContext.ExceptionHandled = true;
                    //}      
                }


                var contentEncoding = filterContext.HttpContext.Request.ContentEncoding ?? Encoding.UTF8;

                if (_jsonTypes.Any(type => acceptTypes.Contains(type)) || filterContext.HttpContext.Request.Url.ToString().ToLower().Contains("callback"))
                    filterContext.Result = new JsonResult2()
                    {
                        Data = model,
                        ContentEncoding = contentEncoding,
                        ContentType = filterContext.HttpContext.Request.ContentType
                    };
            }
            catch (Exception)
            {
                //TBD
                //if (ex.InnerException != null)
                //    throw new DofEException(ex.InnerException.ToString(), ex);
                //else
                //    throw new DofEException(ex.Message, ex);
            }
        }
    }
}
